<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Spring三级缓存 | Sobremesa的个人空间</title><meta name="keywords" content="Java、面试题"><meta name="author" content="Li YunBO"><meta name="copyright" content="Li YunBO"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="Spring三级缓存缓存作用分析Spring中的一级缓存名为singletonObjects，二级缓存名为earlySingletonObjects，三级缓存名为singletonFactories，除了一级缓存是ConcurrentHashMap之外，二级缓存和三级缓存都是HashMap。它们的定义是在DefaultSingletonBeanRegistry类中。 一级缓存：singletonO">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring三级缓存">
<meta property="og:url" content="http://example.com/2021/04/21/%E9%9D%A2%E8%AF%95%E5%BF%85%E8%80%83%E9%A2%98Spring%E7%9A%84%E4%B8%89%E7%BA%A7%E7%BC%93%E5%AD%98%E5%92%8C%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98/index.html">
<meta property="og:site_name" content="Sobremesa的个人空间">
<meta property="og:description" content="Spring三级缓存缓存作用分析Spring中的一级缓存名为singletonObjects，二级缓存名为earlySingletonObjects，三级缓存名为singletonFactories，除了一级缓存是ConcurrentHashMap之外，二级缓存和三级缓存都是HashMap。它们的定义是在DefaultSingletonBeanRegistry类中。 一级缓存：singletonO">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://example.com/img/%E5%A4%B4%E5%83%8F2.jpg">
<meta property="article:published_time" content="2021-04-20T16:00:00.000Z">
<meta property="article:modified_time" content="2021-04-25T09:05:34.670Z">
<meta property="article:author" content="Li YunBO">
<meta property="article:tag" content="Java、面试题">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/img/%E5%A4%B4%E5%83%8F2.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2021/04/21/%E9%9D%A2%E8%AF%95%E5%BF%85%E8%80%83%E9%A2%98Spring%E7%9A%84%E4%B8%89%E7%BA%A7%E7%BC%93%E5%AD%98%E5%92%8C%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  ClickShowText: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-04-25 17:05:34'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'false'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Sobremesa的个人空间" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/%E5%A4%B4%E5%83%8F2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">193</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">25</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">18</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 档案</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Sobremesa的个人空间</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 档案</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring三级缓存</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-04-20T16:00:00.000Z" title="Created 2021-04-21 00:00:00">2021-04-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-04-25T09:05:34.670Z" title="Updated 2021-04-25 17:05:34">2021-04-25</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Spring三级缓存"><a href="#Spring三级缓存" class="headerlink" title="Spring三级缓存"></a>Spring三级缓存</h1><h2 id="缓存作用分析"><a href="#缓存作用分析" class="headerlink" title="缓存作用分析"></a>缓存作用分析</h2><p>Spring中的一级缓存名为singletonObjects，二级缓存名为earlySingletonObjects，三级缓存名为singletonFactories，除了一级缓存是ConcurrentHashMap之外，二级缓存和三级缓存都是HashMap。它们的定义是在DefaultSingletonBeanRegistry类中。</p>
<p>一级缓存：singletonObjects是用来存放就绪状态的Bean。保存在该缓存中的Bean所实现Aware子接口的方法已经回调完毕，自定义初始化方法已经执行完毕，也经过BeanPostProcessor实现类的postProcessorBeforeInitialization、postProcessorAfterInitialization方法处理；</p>
<p>二级缓存：earlySingletonObjects是用来存放早期曝光的Bean，一般只有处于循环引用状态的Bean才会被保存在该缓存中。保存在该缓存中的Bean所实现Aware子接口的方法还未回调，自定义初始化方法未执行，也未经过BeanPostProcessor实现类的postProcessorBeforeInitialization、postProcessorAfterInitialization方法处理。如果启用了Spring AOP，并且处于切点表达式处理范围之内，那么会被增强，即创建其代理对象。</p>
<p>这里额外提一点，普通Bean被增强(JDK动态代理或CGLIB)的时机是在AbstractAutoProxyCreator实现的BeanPostProcessor的postProcessorAfterInitialization方法中，而处于循环引用状态的Bean被增强的时机是在AbstractAutoProxyCreator实现的SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference方法中。</p>
<p>三级缓存：singletonFactories是用来存放创建用于获取Bean的工厂类-ObjectFactory实例。在IoC容器中，所有刚被创建出来的Bean，默认都会保存到该缓存中。</p>
<h2 id="Bean在这三个缓存之间的流转顺序为（存在循环引用）："><a href="#Bean在这三个缓存之间的流转顺序为（存在循环引用）：" class="headerlink" title="Bean在这三个缓存之间的流转顺序为（存在循环引用）："></a>Bean在这三个缓存之间的流转顺序为（存在循环引用）：</h2><p>通过反射创建Bean实例。是单例Bean，并且IoC容器允许Bean之间循环引用，保存到三级缓存中。<br>当发生了循环引用时，从三级缓存中取出Bean对应的ObjectFactory实例，调用其getObject方法，来获取早期曝光Bean，从三级缓存中移除，保存到二级缓存中。<br>Bean初始化完成，生命周期的相关方法执行完毕，保存到一级缓存中，从二级缓存以及三级缓存中移除。</p>
<h2 id="Bean在这三个缓存之间的流转顺序为（没有循环引用）："><a href="#Bean在这三个缓存之间的流转顺序为（没有循环引用）：" class="headerlink" title="Bean在这三个缓存之间的流转顺序为（没有循环引用）："></a>Bean在这三个缓存之间的流转顺序为（没有循环引用）：</h2><p>通过反射创建Bean实例。是单例Bean，并且IoC容器允许Bean之间循环引用，保存到三级缓存中。<br>Bean初始化完成，生命周期的相关方法执行完毕，保存到一级缓存中，从二级缓存以及三级缓存中移除。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>通过以上分析，我们可以得知Bean在一级缓存、二级缓存、三级缓存中的流转顺序为：三级缓存-&gt;二级缓存-&gt;一级缓存。但是并不是所有Bean都会经历这个过程，例如对于原型Bean(Prototype)，IoC容器不会将其保存到任何一个缓存中的，另外即便是单例Bean(Singleton)，如果没有循环引用关系，也不会被保存到二级缓存中的。</p>
<p>————————————————<br>原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/m0_43448868/article/details/113578628">https://blog.csdn.net/m0_43448868/article/details/113578628</a></p>
<p>Spring bean循环依赖即循环引用。是指2个或以上bean 互相持有对方，最终形成闭环。比如A依赖于B，B依赖A。产生循环依赖的方式有两种，一种是通过构造器注入形成的循环依赖，第二种是通过field属性注入形成的循环依赖。Spring通过特殊的bean生成机制解决了第二种方式产生的循环依赖问题，使得循环链的所有bean对象都能正确创建，而构造器注入方式阐释的循环依赖则会抛出异常。两者之间的差异能在bean创建机制中得到解释。</p>
<p>注意此处讨论的bean皆为单例，prototype的bean循环依赖皆会抛出异常，若是单例与prototype混合的情况，若是先创建单例则能成功，反之则会抛出异常。</p>
<p>总的来说，Spring解决循环依赖问题是通过结合bean实例化和bean属性填装分离，singletonObjects、earlySingletonObjects 、singletonFactories 三级缓存机制和引用提前暴露机制实现的。下面将详细介绍单例bean创建与获取过程。</p>
<p>Spring bean三级缓存解决循环依赖<br>Spring能解决bean循环依赖的核心机制即三级缓存，其源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 一级缓存，保存singletonBean实例: bean name --&gt; bean instance */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, Object&gt; singletonObjects = <span class="keyword">new</span> ConcurrentHashMap&lt;String, Object&gt;(<span class="number">256</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 二级缓存，保存早期未完全创建的Singleton实例: bean name --&gt; bean instance */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, Object&gt; earlySingletonObjects = <span class="keyword">new</span> HashMap&lt;String, Object&gt;(<span class="number">16</span>); </span><br><span class="line"></span><br><span class="line"><span class="comment">/** 三级缓存，保存singletonBean生产工厂: bean name --&gt; ObjectFactory */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, ObjectFactory&lt;?&gt;&gt; singletonFactories = <span class="keyword">new</span> HashMap&lt;String, ObjectFactory&lt;?&gt;&gt;(<span class="number">16</span>);</span><br></pre></td></tr></table></figure>


<p>详细源码调用链不再赘述，总体逻辑上，当Spring容器试图获得单例bean时，首先会在三级缓存中查找，具体方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">getSingleton</span><span class="params">(String beanName, <span class="keyword">boolean</span> allowEarlyReference)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 查询一级缓存</span></span><br><span class="line">    Object singletonObject = <span class="keyword">this</span>.singletonObjects.get(beanName);</span><br><span class="line">    <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span> &amp;&amp; isSingletonCurrentlyInCreation(beanName)) &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">            <span class="comment">//若一级缓存内不存在，查询二级缓存</span></span><br><span class="line">            singletonObject = <span class="keyword">this</span>.earlySingletonObjects.get(beanName);</span><br><span class="line">            <span class="keyword">if</span> (singletonObject == <span class="keyword">null</span> &amp;&amp; allowEarlyReference) &#123;</span><br><span class="line">                <span class="comment">//若二级缓存内不存在，查询三级缓存</span></span><br><span class="line">                ObjectFactory&lt;?&gt; singletonFactory = <span class="keyword">this</span>.singletonFactories.get(beanName);</span><br><span class="line">                <span class="keyword">if</span> (singletonFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">//若三级缓存中的，则通过工厂获得对象，并清除三级缓存，提升至二级缓存</span></span><br><span class="line">                    singletonObject = singletonFactory.getObject();</span><br><span class="line">                    <span class="keyword">this</span>.earlySingletonObjects.put(beanName, singletonObject);</span><br><span class="line">                    <span class="keyword">this</span>.singletonFactories.remove(beanName);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> (singletonObject != NULL_OBJECT ? singletonObject : <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<p>查找位置从一级缓存至三级缓存，注意若三级缓存查找成功，其返回的bean对象并不一定是完全体，而可能是仅完成实例化，还未完成属性装填的提前暴露引用。当三级缓存内都未找到目标，getSingleton方法则会返回null，之后Spring将会执行一系列逻辑，最终将调用以下方法新创建bean对象：    </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(<span class="keyword">final</span> String beanName, <span class="keyword">final</span> RootBeanDefinition mbd, <span class="keyword">final</span> <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line">	<span class="comment">//此处略过  做某些事</span></span><br><span class="line">   </span><br><span class="line">	<span class="comment">// Eagerly cache singletons to be able to resolve circular references</span></span><br><span class="line">	<span class="comment">// even when triggered by lifecycle interfaces like BeanFactoryAware.</span></span><br><span class="line">	<span class="comment">// 早期缓存单例对象以解决循环引用问题</span></span><br><span class="line">	<span class="comment">// 即使问题是在如BeanFactoryAware的生命周期阶段接口处发生的</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 允许早期暴露参数</span></span><br><span class="line">	<span class="keyword">boolean</span> earlySingletonExposure = (mbd.isSingleton() &amp;&amp; <span class="keyword">this</span>.allowCircularReferences &amp;&amp;</span><br><span class="line">			isSingletonCurrentlyInCreation(beanName));</span><br><span class="line">	<span class="keyword">if</span> (earlySingletonExposure) &#123;</span><br><span class="line">		<span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">			logger.trace(<span class="string">&quot;Eagerly caching bean &#x27;&quot;</span> + beanName +</span><br><span class="line">					<span class="string">&quot;&#x27; to allow for resolving potential circular references&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 将实例化完成但还未填装属性的bean引用暴露出来，方法为将beanName和对应singletonFactory加入第三级缓存Map</span></span><br><span class="line">		addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Initialize the bean instance.</span></span><br><span class="line">	Object exposedObject = bean;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 此处省略部分代码</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">//填装属性，在此方法内尝试获得循环引用的被引用bean，方法与自身bean获得流程一致</span></span><br><span class="line">	populateBean(beanName, mbd, instanceWrapper);</span><br><span class="line">	exposedObject = initializeBean(beanName, exposedObject, mbd);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 此处省略部分代码</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>以上则是解决循环引用问题的关键：<strong>在初次创建Bean对象的过程中，当bean实例化完成后并不直接开始属性装配，而是先检查是否允许提前暴露，若允许则通过将对应SingletonFactory加入第三级Bean缓存使得外界能够提前获得该Bean的未完成引用，之后再进行属性装配工作。</strong>通过上述执行流程，循环引用问题得以解决：<br>1、设A、B单例对象相互依赖，当我们试图获得A对象时，将首先根据BeanName在三级缓存中查找，显然目前是查询不到的。<br>2、之后将执行doCreateBean方法创建新的A对象，在实例化但未完成属性装配时，方法会通过将对应SingletonFactory将A-Bean的引用提前暴露出去，然后执行属性装配。<br>3、在属性装配方法中，发现A依赖于B，随机尝试获得B-bean，调用getSingleton方法查询三级缓存，结果依然是未找到B-bean，于是和A流程一样调用doCreateBean方法创建一个新的B-bean。<br>4、此处与doCreateBean方法创建A-bean流程一致，成功实例化B-bean但未填装属性，将早期引用暴露，执行属性填装方法，发现B依赖于A，于是试图获得A-bean。<br>5、<strong>差异在此处出现，由于第三步已经将A-bean的早期引用通过第三级缓存暴露出来，在此处执行getSingleton方法时将会成功在三级缓存内获得A-bean引用，由此递归地返回，先后完成B-bean的属性装填工作，B-bean的创建工作，A-Bean的属性装填工作，最后完成A-Bean的创建工作。</strong></p>
<p>由此通过属性注入的循环依赖问题得以解决，同时上述流程也解释了为何通过构造器注入产生的循环依赖问题会抛出异常，因为在A-bean执行构造方法的时候即需要获得B-bean方法。</p>
<p>另外bean对象在某些场景下会在三级缓存间迁徙，非本文论述重点，不再讨论。</p>
<p>为何使用三级缓存而非二级<br>学习解决循环依赖机制过程中便有一个疑问：将缓存分为三级是否有必要，依据处理流程，二级缓存似乎也能很好解决循环依赖问题。查证之后发现许多人也有和我一样的疑问，但很难找到一个权威的解答，最终找到一篇博客给出了令我信服的说法：</p>
<p><strong>使用三级缓存而非二级缓存并不是因为只有三级缓存才能解决循环引用问题，其实二级缓存同样也能很好解决循环引用问题。使用三级而非二级缓存并非出于IOC的考虑，而是出于AOP的考虑，即若使用二级缓存，在AOP情形下，注入到其他bean的，不是最终的代理对象，而是原始对象。</strong></p>
<p>相关链接如下：<br><a target="_blank" rel="noopener" href="https://my.oschina.net/u/4340310/blog/4332450">https://my.oschina.net/u/4340310/blog/4332450</a><br>————————————————<br>原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/panda9527z/article/details/107359916">https://blog.csdn.net/panda9527z/article/details/107359916</a></p>
<p><a href="https://link.zhihu.com/?target=https://juejin.cn/post/6930904292958142478%23heading-5">三级缓存和循环依赖(不看点源码都看不懂)juejin.cn</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Li YunBO</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://example.com/2021/04/21/%E9%9D%A2%E8%AF%95%E5%BF%85%E8%80%83%E9%A2%98Spring%E7%9A%84%E4%B8%89%E7%BA%A7%E7%BC%93%E5%AD%98%E5%92%8C%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98/">http://example.com/2021/04/21/%E9%9D%A2%E8%AF%95%E5%BF%85%E8%80%83%E9%A2%98Spring%E7%9A%84%E4%B8%89%E7%BA%A7%E7%BC%93%E5%AD%98%E5%92%8C%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java%E3%80%81%E9%9D%A2%E8%AF%95%E9%A2%98/">Java、面试题</a></div><div class="post_share"><div class="social-share" data-image="/img/%E5%A4%B4%E5%83%8F2.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/04/21/%E9%9D%A2%E8%AF%95%E5%BF%85%E8%80%83%E9%A2%98Spring%E4%B8%ADjdk%E5%92%8Cgblib%E7%9A%84%E5%8C%BA%E5%88%AB/"><img class="prev-cover" src="/" onerror="onerror=null;src='/img/404.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">Spring中jdk和gblib的区别</div></div></a></div><div class="next-post pull-right"><a href="/2021/04/21/%E9%9D%A2%E8%AF%95%E5%BF%85%E8%80%83%E9%A2%98https%E7%9A%84s%E6%98%AF%E4%BB%80%E4%B9%88/"><img class="next-cover" src="/" onerror="onerror=null;src='/img/404.png'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">HTTPS的S是什么</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2021/04/21/面试必考题B+索引比B索引好在哪？/" title="B+树相比B树的优势"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-21</div><div class="title">B+树相比B树的优势</div></div></a></div><div><a href="/2021/04/21/面试必考题Spring中jdk和gblib的区别/" title="Spring中jdk和gblib的区别"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-21</div><div class="title">Spring中jdk和gblib的区别</div></div></a></div><div><a href="/2021/04/21/面试必考题https的s是什么/" title="HTTPS的S是什么"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-21</div><div class="title">HTTPS的S是什么</div></div></a></div><div><a href="/2021/04/21/面试必考题乐观锁怎么实现/" title="乐观锁怎么实现？"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-21</div><div class="title">乐观锁怎么实现？</div></div></a></div><div><a href="/2021/04/21/面试必考题关键volatile的作用/" title="java中volatile的作用是什么"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-21</div><div class="title">java中volatile的作用是什么</div></div></a></div><div><a href="/2021/04/21/面试必考题垃圾回收机制/" title="垃圾回收机制"><img class="cover" src="/" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-21</div><div class="title">垃圾回收机制</div></div></a></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" src="/img/%E5%A4%B4%E5%83%8F2.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Li YunBO</div><div class="author-info__description">给自己的警言：不要止步不前，不要因循守缺，不要纸上谈兵，不要不思进取，不要一直不要！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">193</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">25</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">18</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/Sobremesa_bolg"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/Sobremesa_bolg" target="_blank" title="Gitee"><i class="fab fa-github"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">这是我的博客</div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Spring%E4%B8%89%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="toc-number">1.</span> <span class="toc-text">Spring三级缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%93%E5%AD%98%E4%BD%9C%E7%94%A8%E5%88%86%E6%9E%90"><span class="toc-number">1.1.</span> <span class="toc-text">缓存作用分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Bean%E5%9C%A8%E8%BF%99%E4%B8%89%E4%B8%AA%E7%BC%93%E5%AD%98%E4%B9%8B%E9%97%B4%E7%9A%84%E6%B5%81%E8%BD%AC%E9%A1%BA%E5%BA%8F%E4%B8%BA%EF%BC%88%E5%AD%98%E5%9C%A8%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8%EF%BC%89%EF%BC%9A"><span class="toc-number">1.2.</span> <span class="toc-text">Bean在这三个缓存之间的流转顺序为（存在循环引用）：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Bean%E5%9C%A8%E8%BF%99%E4%B8%89%E4%B8%AA%E7%BC%93%E5%AD%98%E4%B9%8B%E9%97%B4%E7%9A%84%E6%B5%81%E8%BD%AC%E9%A1%BA%E5%BA%8F%E4%B8%BA%EF%BC%88%E6%B2%A1%E6%9C%89%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8%EF%BC%89%EF%BC%9A"><span class="toc-number">1.3.</span> <span class="toc-text">Bean在这三个缓存之间的流转顺序为（没有循环引用）：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">1.4.</span> <span class="toc-text">总结</span></a></li></ol></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/08/16/%E6%B5%8B%E8%AF%95%E8%AE%B0%E5%BD%95/" title="测试"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="测试"/></a><div class="content"><a class="title" href="/2021/08/16/%E6%B5%8B%E8%AF%95%E8%AE%B0%E5%BD%95/" title="测试">测试</a><time datetime="2021-08-16T01:20:46.666Z" title="Created 2021-08-16 09:20:46">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/16/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%81%8D%E5%8E%86/" title="二叉树的遍历"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="二叉树的遍历"/></a><div class="content"><a class="title" href="/2021/08/16/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%81%8D%E5%8E%86/" title="二叉树的遍历">二叉树的遍历</a><time datetime="2021-08-15T16:00:00.000Z" title="Created 2021-08-16 00:00:00">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89/" title="认真的 Netty 源码解析（二）"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="认真的 Netty 源码解析（二）"/></a><div class="content"><a class="title" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89/" title="认真的 Netty 源码解析（二）">认真的 Netty 源码解析（二）</a><time datetime="2021-08-10T07:53:27.000Z" title="Created 2021-08-10 15:53:27">2021-08-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89/" title="认真的 Netty 源码解析（一）"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="认真的 Netty 源码解析（一）"/></a><div class="content"><a class="title" href="/2021/08/10/%E8%AE%A4%E7%9C%9F%E7%9A%84+Netty+%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89/" title="认真的 Netty 源码解析（一）">认真的 Netty 源码解析（一）</a><time datetime="2021-08-10T07:53:15.000Z" title="Created 2021-08-10 15:53:15">2021-08-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/10/Java+%E9%9D%9E%E9%98%BB%E5%A1%9E+IO+%E5%92%8C%E5%BC%82%E6%AD%A5+IO/" title="Java 非阻塞 IO 和异步 IO"><img src="/img/%E5%92%8C%E6%9C%8D%E5%B0%91%E5%A5%B3.jpg%20img/%E8%9C%98%E8%9B%9B%E4%BE%A0.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="Java 非阻塞 IO 和异步 IO"/></a><div class="content"><a class="title" href="/2021/08/10/Java+%E9%9D%9E%E9%98%BB%E5%A1%9E+IO+%E5%92%8C%E5%BC%82%E6%AD%A5+IO/" title="Java 非阻塞 IO 和异步 IO">Java 非阻塞 IO 和异步 IO</a><time datetime="2021-08-10T07:52:59.000Z" title="Created 2021-08-10 15:52:59">2021-08-10</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Li YunBO</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginModelPath":"assets/","model":{"jsonPath":"live2d-widget-model-koharu"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":false},"rect":"opacity:0.7","log":false,"pluginJsPath":"lib/","pluginRootPath":"live2dw/","tagMode":false});</script></body></html>